package com.droid.mvvmlib.base;

import java.lang.ref.WeakReference;

/**
 * 基础Model
 * @author zyc0617
 * @since  2019/8/18 15:35
 */
public class SuperBaseModel<T> extends BaseModel<T> {

    protected void loadSuccess(T data, final String ...tag) {
        synchronized (this) {
            mUiHandler.postDelayed(() -> {
                for(WeakReference<IBaseModeListener> weakListener : mWeakLinkArrayList) {
                    if(weakListener.get() instanceof IModelListener) {
                        IModelListener listener = (IModelListener) weakListener.get();
                        if(listener != null){
                            listener.onSuccess(SuperBaseModel.this, data, tag);
                        }
                    }
                }

                // 如果需要缓存数据，加载成功后缓存到preference中
                if(getCachedPreferenceKey() != null) {
                    saveToPreference(data);
                }

            },0);
        }
    }

    protected void loadFail(final String error, final String ...tag) {
        synchronized (this) {
            mUiHandler.postDelayed(() -> {
                for(WeakReference<IBaseModeListener> weakListener : mWeakLinkArrayList) {
                    if(weakListener.get() instanceof IModelListener) {
                        IModelListener listener = (IModelListener) weakListener.get();
                        if(listener != null){
                            listener.onFail(SuperBaseModel.this, error, tag);
                        }
                    }
                }

            },0);
        }
    }


    @Override
    public void refresh() {

    }

    @Override
    protected void load() {

    }

    @Override
    protected void notifyCacheData(T data) {
        loadSuccess(data);
    }

    public interface IModelListener<T> extends IBaseModeListener {

        void onSuccess(SuperBaseModel model, T data, final String... tag);
        void onFail(SuperBaseModel model, String error, final String... tag);
    }
}
